package org.gavin.core.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.gavin.core.advice.HttpServletRequestAdvice;
import org.gavin.core.constant.CommonConst;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * CustomFilter
 *
 * @author grl
 * @date 2024/4/7
 */
@Component
public class CustomFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String contentType = request.getContentType();
        HttpServletRequestAdvice requestAdvice = null;
        if(StringUtils.isNotBlank(contentType) && contentType.startsWith(CommonConst.CONTENT_TYPE_TEXT)){
            requestAdvice = new HttpServletRequestAdvice((HttpServletRequest) servletRequest);
            requestAdvice.addHeader(CommonConst.CONTENT_TYPE_KEY,CommonConst.CONTENT_TYPE_JSON);
        }
        filterChain.doFilter(requestAdvice != null ? requestAdvice : request,servletResponse);
    }
}
